package org.file5.controller.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.file5.domain.Article;
import org.file5.domain.Attachment;
import org.file5.domain.Category;
import org.file5.service.ServiceFascade;
import org.file5.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.googlecode.objectify.Key;

@Controller
@RequestMapping("/admin/article/reprint/{authorBlogUrl}/{authorEmail}/{articleUid}")
@SessionAttributes("article")
public class ReprintArticleForm {
	private final Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private ServiceFascade sf;

	@InitBinder
	public void setAllowedFields(WebDataBinder dataBinder) {
		dataBinder.setDisallowedFields(new String[] { "uid" });
	}

	@RequestMapping(method = RequestMethod.GET)
	public String setupForm(@PathVariable("authorBlogUrl") String authorBlogUrl,
			@PathVariable("authorEmail") String authorEmail, @PathVariable("articleUid") String articleUid,
			ModelMap model) {
		Article article = this.sf.getArticleService().find(articleUid, false);
		if (article == null) {
			article = new Article();
		} else {
			model.addAttribute("articleexist", true);
		}
		model.addAttribute("article", article);
		model.addAttribute("authorBlogUrl", authorBlogUrl);
		model.addAttribute("authorEmail", authorEmail);
		model.addAttribute("articleUid", articleUid);

		return "admin/article/articlereprint";
	}

	@RequestMapping(method = { RequestMethod.PUT, RequestMethod.POST })
	public String processSubmit(@PathVariable("authorBlogUrl") String authorBlogUrl,
			@PathVariable("authorEmail") String authorEmail, @PathVariable("articleUid") String articleUid,
			@ModelAttribute("article") Article article, BindingResult result, SessionStatus status,
			HttpServletRequest request) {

		// new PetValidator().validate(article, result);
		if (result.hasErrors()) {
			return "admin/article/articleedit";
		} else {
			article = sf.getArticleService().addUpdateReprintArticle(article, authorBlogUrl, authorEmail, articleUid);
			if (article != null) {
				sf.getEntityIndexService().addIndexTask(Article.class, article.getUid());
			}
			return "redirect:/admin/article/list.asp";
		}
	}
}
